import java.io.IOException;
import java.net.*;

public class EdpChoServe {
    private DatagramSocket socket = null;
    public EdpChoServe(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器启动");
        while (true){
            //创建接收缓冲区DatagramPacket
            DatagramPacket requestparcket = new DatagramPacket(new byte[1024],1024);
            //接收客户端数据
            socket.receive(requestparcket);
            //将数据转化为字符串类型
            String request = new String(requestparcket.getData(),0, requestparcket.getLength());
            //将转化后的数据通过process方法进行处理（此处直接返回，如果要进行相关数据的处理直接修改process方法）
            String response = process(request);
            //再次创建DatagramPacket套接字，将加工的数据给客户端发送
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(),
                    response.getBytes().length,requestparcket.getSocketAddress());
            //发送数据
            socket.send(responsePacket);
            //打印客户端地址,端口,请求和相应信息
            System.out.printf("[%s:%d] req:%s,resp:%s\n",requestparcket.getAddress().toString(),
                    requestparcket.getPort(),request,response);
        }
    }
    private String process(String request){
        String response = "服务端返回的消息："+request;
        return response;
    }

    public static void main(String[] args) throws IOException {
        EdpChoServe serve = new EdpChoServe(1010);
        serve.start();
    }
}
